#include "ejattrset.h"
#include "ejcommon.h"
#include "ejstylesheet.h"
#include "ejconfigmanager.h"

#include <QFile>
#include <QSplitter>
#include <QHeaderView>
#include <QGridLayout>
#include <QMessageBox>

#include <QVector>
#include <QLabel>
#include <QPushButton>

#include <QDebug>

#include "ejsqlmanager.h"
#include "ejeffectdelegate.h"
#include "ejeffecteddelegate.h"

EJAttrSet::EJAttrSet(QWidget *parent) : QMainWindow(parent)
{
    auto mainSplitter = new QSplitter(Qt::Vertical, this);
    mainSplitter->setHandleWidth(1);
    setCentralWidget(mainSplitter);

    auto cnfManager = EJConfigManager::getInstance();
    if (!cnfManager->addConfig(XLMNAME))
    {
        auto ret = QMessageBox::question(NULL, tr("警告"), tr("没有找到文件") + XLMNAME + tr(", 是否继续？"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        if (ret == QMessageBox::No) close();
    }

    QStringList gList = QStringList() << tr("UI") << tr("Base") << tr("GloabalWidget");
    QStringList bList = QStringList() << tr("UI") << tr("Base") << tr("BaseWidiget");

    auto globalName = EJConfigManager::getAttrByName(XLMNAME, gList, tr("name"));
    auto baseName   = EJConfigManager::getAttrByName(XLMNAME, bList, tr("name"));

    auto dbName      = EJConfigManager::getAttrByName(XLMNAME, QStringList() << tr("UI"), tr("dbname"));
    auto dbpasswd    = EJConfigManager::getAttrByName(XLMNAME, QStringList() << tr("UI"), tr("dbpasswd"));
    auto globalView = EJConfigManager::getAttrByName(XLMNAME, gList, tr("table"));
    auto baseView   = EJConfigManager::getAttrByName(XLMNAME, bList, tr("table"));

    auto gloHead = EJConfigManager::getValueByName(XLMNAME, gList, tr("Field"));
    auto baseHead = EJConfigManager::getValueByName(XLMNAME, bList, tr("Field"));

    auto gloAttr  = EJConfigManager::getAttr(XLMNAME, gList, tr("Field"), tr("chk"));
    auto baseAttr = EJConfigManager::getAttr(XLMNAME, bList, tr("Field"), tr("inf"));

    auto gloType  = EJConfigManager::getAttr(XLMNAME, gList, tr("Field"), tr("type"));
    auto baseType = EJConfigManager::getAttr(XLMNAME, bList, tr("Field"), tr("type"));

    auto sm = EJSqlManager::getInstance();
    sm->open(dbpasswd, dbName);
    sm->setDefaultDB(dbName);
    sm->setDefaultTB(globalView);  //baseView

    if (!sm->existTable())
    {
        sm->createTable(gloHead);
        sm->createTable(baseHead, baseView);
    }

    EJ_CRE_GROUP(m_global, globalName, mainSplitter, globalView)
    EJ_CRE_GROUP(m_base, baseName, mainSplitter, baseView)

    EJ_SET_GROUP(m_global)
    EJ_SET_GROUP(m_base)

    //m_globalView->verticalHeader()->hide();

    m_globalView->setEditTriggers(QAbstractItemView::CurrentChanged); /*设置单击编辑*/
    m_baseView->setEditTriggers(QAbstractItemView::CurrentChanged); /*设置单击编辑*/

    //m_baseView->setSelectionBehavior(QAbstractItemView::SelectRows);

    m_globalView->setContextMenuPolicy(Qt::CustomContextMenu);
    m_baseView->setContextMenuPolicy(Qt::CustomContextMenu);

    connect(m_globalView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(OnGlobalPopMenu(QPoint)));
    connect(m_baseView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(OnBasePopMenu(QPoint)));

    auto addCol = new QAction(tr("添加列"), this);
    connect(addCol, SIGNAL(triggered(bool)), this, SLOT(OnAddCol()));
    /*创建全局view菜单*/
    m_popGlobalMenu = new QMenu(this);

    auto addGlobal = new QAction(tr("添加行"), this);
    connect(addGlobal, SIGNAL(triggered(bool)), this, SLOT(OnGlobalAdd()));
    auto delGlobal = new QAction(tr("删除行"), this);
    connect(delGlobal, SIGNAL(triggered(bool)), this, SLOT(OnGlobalDel()));
    auto saveGlobalData = new QAction(tr("提交修改"), this);
    connect(saveGlobalData, SIGNAL(triggered(bool)), this, SLOT(OnSaveGlobalData()));

    m_popGlobalMenu->addAction(addGlobal);
    m_popGlobalMenu->addAction(delGlobal);
    m_popGlobalMenu->addSeparator();
    m_popGlobalMenu->addAction(saveGlobalData);
    //m_popGlobalMenu->addSeparator();
    //m_popGlobalMenu->addAction(addCol);

    /*创建基础菜单*/
    m_popBaseMenu = new QMenu(this);

    auto addBase = new QAction(tr("添加行"), this);
    connect(addBase, SIGNAL(triggered(bool)), this, SLOT(OnBaseAdd()));

    auto delBase = new QAction(tr("删除行"), this);
    connect(delBase, SIGNAL(triggered(bool)), this, SLOT(OnBaseDel()));
    auto saveBaseData = new QAction(tr("提交修改"), this);
    connect(saveBaseData, SIGNAL(triggered(bool)), this, SLOT(OnSaveBaseData()));

    m_popBaseMenu->addAction(addBase);
    m_popBaseMenu->addAction(delBase);
    m_popBaseMenu->addSeparator();
    m_popBaseMenu->addAction(saveBaseData);
    //m_popBaseMenu->addSeparator();
    //m_popBaseMenu->addAction(addCol);

    /*设置代理*/
    int effected = -1;
    for (int i = 0; i < gloAttr.size(); i++)
    {
        if (gloAttr.at(i) == "1")
        {
            auto delegate = new EJEffectedDelegate;
            connect(delegate, SIGNAL(clicked(bool,QModelIndex)), this, SLOT(OnEffectedChang(bool,QModelIndex)));
            m_globalView->setItemDelegateForColumn(i, delegate);
            effected = i;
        }

        if (gloType.at(i) == "1")
        {
            m_globalView->setItemDelegateForColumn(i, new EJEffectDelegate(QStringList() << tr("int") << tr("string")));
        }
    }
    int row = m_globalModel->rowCount();
    QStringList efftecedNameZN, efftecedNameEN;

    for (int i = 0; i < row; i++)
    {
        if (m_globalModel->index(i, effected).data().toBool())
        {
            efftecedNameZN << m_globalModel->index(i, 0).data().toString();
            efftecedNameEN << m_globalModel->index(i, 1).data().toString();
        }
    }

    QVector<int> effect;
    for (int i = 0; i < baseAttr.size(); i++)
    {
        if (baseAttr.at(i) == "1")
        {
            m_baseView->setItemDelegateForColumn(i, new EJEffectDelegate(efftecedNameZN));
            effect.push_back(i);
        }

        if (baseType.at(i) == "1")
        {
            m_baseView->setItemDelegateForColumn(i, new EJEffectDelegate(QStringList() << tr("int") << tr("string")));
        }
    }

}

void EJAttrSet::OnGlobalAdd()
{
    int rowIndex = m_globalModel->rowCount();
    m_globalModel->insertRow(rowIndex);
    m_globalModel->submitAll();
}

void EJAttrSet::OnGlobalDel()
{
    int curRow = m_globalView->currentIndex().row();
    if (curRow == -1) return ;

    //删除该行
    int ok = QMessageBox::warning(this,tr("删除当前行!"),tr("你确定删除当前行吗？"), QMessageBox::Yes,QMessageBox::No);
    if(ok == QMessageBox::No)
    {
        m_globalModel->revertAll(); //如果不删除，则撤销
    }
    else
    {
        //获取选中的行
        m_globalModel->removeRow(curRow);
        m_globalModel->submitAll(); //否则提交，在数据库中删除该行
    }
    m_globalModel->select();
    m_globalView->reset();
    m_globalView->setModel(m_globalModel);
}

void EJAttrSet::OnGlobalHeaderClicked(int)
{
    qDebug("test");
}

void EJAttrSet::OnBaseAdd()
{
    int rowIndex = m_baseModel->rowCount();
    m_baseModel->insertRow(rowIndex);
    m_baseModel->submitAll();
}

void EJAttrSet::OnBaseDel()
{
    int curRow = m_baseView->currentIndex().row();
    if (curRow == -1) return ;

    //删除该行
    int ok = QMessageBox::warning(this,tr("删除当前行!"),tr("你确定删除当前行吗？"),
                         QMessageBox::Yes,QMessageBox::No);
    if(ok == QMessageBox::No)
    {
        m_baseModel->revertAll(); //如果不删除，则撤销
    }
    else
    {
        //获取选中的行
        m_baseModel->removeRow(curRow);
        m_baseModel->submitAll(); //否则提交，在数据库中删除该行
    }
    m_baseModel->select();
    m_baseView->reset();
    m_baseView->setModel(m_globalModel);
}

void EJAttrSet::OnBaseHeaderClicked(int)
{

}

void EJAttrSet::OnGlobalPopMenu(QPoint)
{
    m_popGlobalMenu->move(QCursor::pos());
    m_popGlobalMenu->exec();
}

void EJAttrSet::OnBasePopMenu(QPoint)
{
    m_popBaseMenu->move(QCursor::pos());
    m_popBaseMenu->exec();
}

void EJAttrSet::OnSaveGlobalData()
{
    int curRow = m_globalView->currentIndex().row();
    if (curRow != -1) m_globalModel->submitAll();
}

void EJAttrSet::OnSaveBaseData()
{
    int curRow = m_baseView->currentIndex().row();
    if (curRow != -1) m_baseModel->submitAll();
}

void EJAttrSet::OnAddCol()
{
    EJAddViewColumn ctc;

    connect(&ctc, SIGNAL(addViewColumn(AddViewColumnEvent*)), this, SLOT(OnAddViewColumn(AddViewColumnEvent*)));

    ctc.exec();
}

void EJAttrSet::OnAddViewColumn(AddViewColumnEvent *event)
{
    qDebug("ColName [%s]", event->columnName.toUtf8().data());

    switch (event->attrType)
    {
    case 0:  /*全局属性*/
        CreateColumn(m_globalView, m_globalModel, event->columnName.toUtf8().data(), 0, new EJEffectedDelegate);
        break;
    case 1:  /*基础属性*/
        CreateColumn(m_baseView, m_baseModel, event->columnName.toUtf8().data(), 1, new EJEffectDelegate);
        break;
    default:
        break;
    }
}

void EJAttrSet::OnEffectedChang(bool check, const QModelIndex index)
{
    m_globalModel->select();
    m_globalView->reset();
    m_globalView->setModel(m_globalModel);

    QStringList bList = QStringList() << tr("UI") << tr("Base") << tr("BaseWidiget");
    auto baseAttr = EJConfigManager::getAttr(XLMNAME, bList, tr("Field"), tr("inf"));
    auto name = m_globalModel->index(index.row(), 0).data().toString();
    if (name.length() == 0 ) return ;

    for (int i = 0; i < baseAttr.size(); i++)
    {
        if (baseAttr.at(i) == "1")
        {
            auto delegate = static_cast<EJEffectDelegate *>(m_baseView->itemDelegateForColumn(i));
            if (check)/*增加*/
            {
                delegate->getItems() << name;
            }
            else/*减少*/
            {
                delegate->getItems().removeOne(name);
            }
        }
    }
}

void EJAttrSet::CreateColumn(QTableView *view, QSqlTableModel *model, const QString &name, int inf, QAbstractItemDelegate *deleGate)
{

    int column = model->columnCount();
    model->insertColumn(column);
    model->setHeaderData(column, Qt::Horizontal, name);
    if (!deleGate) deleGate = new QItemDelegate;
    view->setItemDelegateForColumn(column, deleGate);
    if (inf == 0)
    {

    }

}


EJAddViewColumn::EJAddViewColumn(EJAddViewColumn::AddViewColumnType type, QWidget *parent, Qt::WindowFlags f)
    :QDialog(parent, f)
{
    setWindowTitle(tr("添加列"));

    auto attrTypeLab = new QLabel(tr("属性类别"),this);
    m_attrTypeBox = new QComboBox(this);

    auto attrNameLab = new QLabel(tr("列名称"), this);
    m_attrNameEdt = new QLineEdit(this);

    auto attrInfLab  = new QLabel("是否被影响", this);
    m_attrInfBox  = new QComboBox(this);

    auto confirmBtn  = new QPushButton(tr("确认"), this);
    auto cancelBtn   = new QPushButton(tr("取消"), this);


    m_attrTypeBox->addItems(QStringList() << tr("全局属性") << tr("基础属性"));
    m_attrInfBox->addItems(QStringList() << tr("否") << tr("是"));

    m_attrTypeBox->setCurrentIndex(type);
    if (type == BASE) attrInfLab->setText(tr("是否影响"));

    auto pLayout = new QGridLayout;

    pLayout->addWidget(attrTypeLab, 0, 0, 2, 1);
    pLayout->addWidget(m_attrTypeBox, 0, 1, 2, 1);
    pLayout->addWidget(attrNameLab, 2, 0, 2, 1);
    pLayout->addWidget(m_attrNameEdt, 2, 1, 2, 1);
    pLayout->addWidget(attrInfLab, 4, 0, 2 ,1);
    pLayout->addWidget(m_attrInfBox, 4, 1, 2, 1);

    pLayout->addWidget(confirmBtn, 0, 2, 3, 1);
    pLayout->addWidget(cancelBtn , 3, 2, 3, 1);
    // 设置水平间距
    pLayout->setHorizontalSpacing(10);
    // 设置垂直间距
    pLayout->setVerticalSpacing(10);
    // 设置外间距
    pLayout->setContentsMargins(10, 10, 10, 10);
    setLayout(pLayout);

    connect(confirmBtn, SIGNAL(clicked(bool)), this, SLOT(OnConfirm()));
    connect(cancelBtn, SIGNAL(clicked(bool)), this, SLOT(OnConfirm()));
}

void EJAddViewColumn::OnConfirm()
{
    AddViewColumnEvent *event = new AddViewColumnEvent;
    event->attrType = m_attrTypeBox->currentIndex();
    event->columnName = m_attrNameEdt->text();
    event->isIfc = m_attrInfBox->currentIndex();

    emit addViewColumn(event);
    done(QDialog::Accepted);
}

void EJAddViewColumn::OnCancel()
{
    done(QDialog::Rejected);
}


